package ch7

import (
	"math/rand"
	"time"
)

// doCompute 是实际运算函数，这里进行一些人为设置的等待时间
func doCompute(x int) int {
	time.Sleep(time.Duration(rand.Intn(10)) * time.Millisecond)
	return 1 + x
}

// branch 开分支的逻辑，并将运算结果保存到通道中
func branch(x int) chan int {
	ch := make(chan int)
	go func() {
		ch <- doCompute(x)
	}()
	return ch
}

// 将输入通道的结果传入通道并返回
func Recombination(chs ...chan int) chan int {
	ch := make(chan int)
	for _, c := range chs {
		go func(c chan int) {
			ch <- <-c
		}(c)
	}
	return ch
}

func Recombination1(chs... chan int) chan int {
	ch := make(chan int)
	go func() {
		for i := 0; i < len(chs); i++ {
			select {
			case v1 := <-chs[i]:
				ch <- v1
			default:
			}
		}
	}()
	return ch
}
